package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.LogToDB
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 乙方合同签署结果回调
 * 乙方完成全部签署后推送甲方签署
 */

public class apiContractCallback implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiContractCallback.class);
    private String LOCALURL = "";
    private String charset = "utf-8"; // 设置字符集
    private int timeout = 100000; // 设置请求超时时间
    private int enableSSLflag = 0;
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        //获取回调类型
        String callbacktype = request.getParameter("callbacktype");
        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }
        log.info("[调用请求信息]:" + callJson);

        if (callbacktype.equals("cust")) {
            return custcallback(eliteBean, callJson); //乙方签署回调
        }else if(callbacktype.equals("admin")){
            return admincallback(eliteBean, callJson); //甲方签署回调
        }

    }

    //乙方签署回调方法
    public String custcallback(EliteBean eliteBean,String callJson) {
        long startTime = System.currentTimeMillis();
        // 初始化返回参数
        JSONObject result = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        try {
            JSONObject inJson = JSONObject.fromObject(callJson);
            String bizContents = inJson.getString("bizContent");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(bizContents);
            log.debug("bizContent解密：" + new String(bytes))
            String bizContent = URLDecoder.decode(new String(bytes), "UTF-8");
            log.debug("bizContent转码：" + bizContent);
            JSONObject bizContentJson = JSONObject.fromObject(bizContent);
            LOCALURL = KHDBConfig.getAPIURL(eliteBean, "Groovy-Inner");

            String docNo = bizContentJson.getString("docNo");   //获取合同编号
            String transactionNo = bizContentJson.getString("transactionNo");   //获取接入平台交易号
            String resultCode = bizContentJson.getString("resultCode"); //获取状态码
            String resultMsg = bizContentJson.getString("resultMsg"); //获取状态描述

            //数据处理
            if (resultCode == '1' || resultCode == '10040019') { //签署成功 || 已转签
                eliteBean.update("update fdd_agreement_list set ht_state = '已签署', ht_statetime = now(), resultCode = '"+resultCode+"', resultMsg = '"+resultMsg+"', resultTime = now() where transactionNo='"+transactionNo+"'", "dataSource");
            }else if(resultCode == '2' ){ //已拒签
                eliteBean.update("update fdd_agreement_list set ht_state = '已拒签', rejectionReason='"+bizContentJson.getString("rejectionReason")+"', resultCode = '"+resultCode+"', resultMsg = '"+resultMsg+"', resultTime = now() where transactionNo='"+transactionNo+"'", "dataSource");
            }else{
                eliteBean.update("update fdd_agreement_list set resultCode = '"+resultCode+"', resultMsg = '"+resultMsg+"', resultTime = now() where transactionNo='"+transactionNo+"'", "dataSource");
            }

            //检查是否存在客户未签署
            List custlist = eliteBean.chaxun_sql("select workorderid from fdd_agreement_list where contractid='"+docNo+"' and ht_state='未签署' and ht_type='客户'", "dataSource");
            //查找合同对应工单ID
            List workorderidlist = eliteBean.chaxun_sql("select workorderid, ht_type from fdd_agreement_list where contractid='"+docNo+"' order by ordernum asc", "dataSource");
            String workorderid = workorderidlist[0].get("workorderid");

            //如果乙方已全部签署，则推送甲方印章管理员签署
            if(custlist.size()==0){
                //推送甲方签署
                String pushurl = LOCALURL+'/api/apiCreateContract?interfacetype=pushAdmin';
                JSONObject jsonPara = new JSONObject();
                jsonPara.put("workroderid", workorderid);
                String Assemblys = Util.doHttpPostUseHead(pushurl, jsonPara.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);
                JSONObject obj = JSONObject.fromObject(Assemblys);
                //如果code为1则标识当前客户已推送，等待签署后回调
                if(obj.getString("code") == '1') {
                    //查找乙方签署完成后的顺位第一角色
                    List ht_typelist = eliteBean.chaxun_sql("select ht_type from fdd_agreement_list where contractid='"+docNo+"' and ht_type!='客户' order by ordernum asc", "dataSource");
                    String ht_type = ht_typelist[0].get("ht_type");
                    String signingresults = ht_type+"未签署";
                    log.debug("乙方signingresults:"+signingresults+"----"+ht_type);
                    eliteBean.update("update objective set signingresults='"+signingresults+"' where workorderid='" + workorderid + "'", "dataSource");
                }
            }
            result.put("code", "0");
            result.put("msg", "回调成功");
        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "合同签署结果回调", "apiContractCallback", callJson, result.toString(), (System.currentTimeMillis() - startTime).toString(), "/");
        }
        return result.toString();
    }

//甲方签署回调方法
    public String admincallback(EliteBean eliteBean,String callJson) {
        long startTime = System.currentTimeMillis();
        // 初始化返回参数
        JSONObject result = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        try {
            JSONObject inJson = JSONObject.fromObject(callJson);
            String bizContents = inJson.getString("bizContent");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(bizContents);
            log.debug("bizContent解密：" + new String(bytes))
            String bizContent = URLDecoder.decode(new String(bytes), "UTF-8");
            log.debug("bizContent转码：" + bizContent);
            JSONObject bizContentJson = JSONObject.fromObject(bizContent);
            LOCALURL = KHDBConfig.getAPIURL(eliteBean, "Groovy-Inner");

            String docNo = bizContentJson.getString("docNo");   //获取合同编号
            String transactionNo = bizContentJson.getString("transactionNo");   //获取接入平台交易号
            String resultCode = bizContentJson.getString("resultCode"); //获取状态码
            String resultMsg = bizContentJson.getString("resultMsg"); //获取状态描述

            //数据处理
            if (resultCode == '1' || resultCode == '10040019') { //签署成功 || 已转签
                eliteBean.update("update fdd_agreement_list set ht_state = '已签署', ht_statetime = now(), resultCode = '"+resultCode+"', resultMsg = '"+resultMsg+"', resultTime = now() where transactionNo='"+transactionNo+"'", "dataSource");
            }else if(resultCode == '2' ){ //已拒签
                eliteBean.update("update fdd_agreement_list set ht_state = '已拒签', rejectionReason='"+bizContentJson.getString("rejectionReason")+"', resultCode = '"+resultCode+"', resultMsg = '"+resultMsg+"', resultTime = now() where transactionNo='"+transactionNo+"'", "dataSource");
            }else{
                eliteBean.update("update fdd_agreement_list set resultCode = '"+resultCode+"', resultMsg = '"+resultMsg+"', resultTime = now() where transactionNo='"+transactionNo+"'", "dataSource");
            }

            //检查是否存在甲方未签署
            List custlist = eliteBean.chaxun_sql("select workorderid,ht_type from fdd_agreement_list where contractid='"+docNo+"' and ht_state='未签署' and ht_type!='客户' order by ordernum asc", "dataSource");
            //查找合同对应工单ID
            List workorderidlist = eliteBean.chaxun_sql("select workorderid from fdd_agreement_list where contractid='"+docNo+"'", "dataSource");
            String workorderid = workorderidlist[0].get("workorderid");
            String ht_type = custlist[0].get("ht_type");

            //如果甲方未全部签署，则继续推送甲方签署，如此循环
            if(custlist.size()>0){
                //推送甲方签署
                String pushurl = LOCALURL+'/api/apiCreateContract?interfacetype=pushAdmin';
                JSONObject jsonPara = new JSONObject();
                jsonPara.put("workroderid", workorderid);
                String Assemblys = Util.doHttpPostUseHead(pushurl, jsonPara.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);
                JSONObject AssemblysJson = JSONObject.fromObject(Assemblys);
                String code = AssemblysJson.getString("code");
                if(code=="1"){
                    result.put("code", "0");
                    result.put("msg", "回调成功");
                    String signingresults = ht_type+"未签署";
                    log.debug("signingresults:"+signingresults+"----"+ht_type);
                    eliteBean.update("update objective set signingresults='"+signingresults+"' where workorderid='" + workorderid + "'", "dataSource");
                }else{
                    result.put("code", "-1");
                    result.put("msg", "回调失败");
                }
            //甲方已全部签署
            }else{
                eliteBean.update("update objective set signingresults='已签署' where workorderid='" + workorderid + "'", "dataSource");
                eliteBean.update("update fdd_contract_list set signingresults='1' where contractid='"+docNo+"'", "dataSource");
                result.put("code", "0");
                result.put("msg", "回调成功");
            }

        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "合同签署结果回调", "apiContractCallback", callJson, result.toString(), (System.currentTimeMillis() - startTime).toString(), "/");
        }
        return result.toString();
    }

    //获取bizContent
    public static String getbizContent(String param) {
        log.debug("param:" + param);
        String encodedObject = URLEncoder.encode(param, "UTF-8");
        String biz_contents = new BASE64Encoder().encodeBuffer(encodedObject.getBytes("UTF-8"));
        log.info("[biz_contents]:" + biz_contents);
        return biz_contents;
    }
}
